<template>
    <view>
        <view v-if="goods_list.length > 0" class="page">
			<view class="padding-horizontal-main padding-top-main bottom-line-exclude">
				<!-- 地址 -->
				<view class="bg-white border-radius-main" v-if="goods_list[0].type == 0">
					<!-- 销售+自提 模式选择 -->
					<view v-if="common_site_type == 4" class="buy-header-nav oh tc">
					    <block v-for="(item, index) in buy_header_nav" :key="index">
					        <view :class="'item fl ' + (site_model == item.value ? 'cr-main' : 'cr-666')" :data-value="item.value" @tap="buy_header_nav_event">{{ item.name }}</view>
					    </block>
					</view>
					<view class="address bg-white arrow-right" :class="(common_site_type != 4) ? 'border-radius-main' : ''" @tap="address_event">
					    <view v-if="address != null">
					        <view class="address-base oh">
					            <text v-if="(address.alias || null) != null" class="address-alias">{{ address.alias }}</text>
					            <text>{{ address.name }}</text>
					            <text class="fr">{{ address.tel }}</text>
					        </view>
					        <view class="address-detail oh">
								<image class="icon fl" :src="scorestore_static_url+'mini/user-address.png'" mode="widthFix" />
					            <view class="text fr">{{ address.province_name }}{{ address.city_name }}{{ address.county_name }}{{ address.address }}</view>
					        </view>
					    </view>
					    <view v-if="address == null" class="no-address cr-888">
					        {{ site_model == 0 ? $t('buy.buy.6rk813') : $t('buy.buy.wq7gnb') }}
					    </view>
					</view>
					<view class="address-divider spacing-mb"></view>
				</view>
				
				<!-- 商品 -->
				<view class="goods bg-white spacing-mb border-radius-main padding-main">
					<view class="goods-item oh" v-for="(item, index) in goods_list" :key="item.key">
						<image class="goods-image fl" :src="item.images" mode="aspectFill" />

						<view class="goods-base">
							<view class="goods-title multi-text">{{ item.title }}</view>
							<block v-if="item.spec != null">
								<view class="goods-spec cr-888" v-for="(spec, index1) in item.spec" :key="spec.key">{{ spec.type }}:{{ spec.value }}</view>
							</block>
						</view>

						<view class="oh goods-price">
							<text class="sales-price">积分{{ item.price }}</text>
							<text v-if="item.original_price > 0" class="original-price">￥{{ item.original_price }}</text>
							<text class="buy-number cr-888">x{{ item.stock }}</text>
						</view>
					</view>
				</view>

				<!-- 留言 -->
				<textarea @input="bind_user_note_event" maxlength="60" auto-height placeholder="留言" class="content-textarea bg-white spacing-mb border-radius-main" />

				<!-- 扩展数据展示 -->
				<view v-if="extension_data.length > 0" class="extension-list spacing-mb border-radius-main">
					<view class="item oh" v-for="(item, index) in extension_data" :key="item.key">
						<text class="cr-666 fl">{{ item.name }}</text>

						<text class="text-tips fr">{{ item.tips }}</text>
					</view>
				</view>

				<!-- 支付方式 -->
				<view v-if="payment_list.length > 0 && common_order_is_booking != 1" class="payment-list bg-white oh spacing-mb" style="display: none">
					<view class="item tc fl" v-for="(item, index) in payment_list" :key="item.key">
						<view :class="'item-content br ' + (item.selected || '')" :data-value="item.id" @click="payment_event">
							<image v-if="(item.logo || null) != null" class="icon" :src="item.logo" mode="widthFix" />
							<text>{{ item.name }}</text>
						</view>
					</view>
				</view>

				<!-- 积分抵扣 -->
				<view class="payment-list bg-white oh border-radius-main padding-main">
					<view class="weui-cells weui-cells_after-title">
						<label class="weui-cell weui-check__label">
							<view class="weui-cell__bd">
								您的积分余额：{{ user_score }}
								<text v-if="have_no_much_score">（您的积分余额不足）</text>
							</view>
						</label>
					</view>
				</view>
			</view>

            <!-- 导航 -->
            <view class="buy-nav oh wh-auto bg-white bottom-line-exclude">
                <view class="nav-base bg-white fl single-text">
                    <text>合计：</text>
                    <text class="sales-price">{{ total_price }}积分</text>
                </view>
                <view class="fr nav-submit">
                    <button class="bg-main wh-auto" type="default" @click="buy_submit_event" :disabled="buy_submit_disabled_status" hover-class="none">提交订单</button>
                </view>
            </view>
        </view>
        <view v-else>
            <component-no-data :prop-status="data_list_loding_status" :prop-msg="data_list_loding_msg"></component-no-data>
        </view>
    </view>
</template>

<script>
	import componentPopup from '@/components/popup/popup';
	import componentQuickNav from "@/components/quick-nav/quick-nav";
	import componentBadge from '@/components/badge/badge';
	import componentNoData from "@/components/no-data/no-data";
	import componentBottomLine from "@/components/bottom-line/bottom-line";
	import componentOnlineService from "@/components/online-service/online-service";
	
const app = getApp();

var scorestore_static_url = app.globalData.get_static_url('scorestore', true);
var common_static_url = app.globalData.get_static_url('common');
export default {
	components: {
	    componentPopup,
		componentQuickNav,
		componentBadge,
		componentNoData,
		componentBottomLine,
		componentOnlineService
	},
    data() {
        return {
			scorestore_static_url: scorestore_static_url,
			common_static_url: common_static_url,
            data_list_loding_status: 1,
            buy_submit_disabled_status: false,
            data_list_loding_msg: '',
            params: null,
            payment_list: [],
            goods_list: [],
            address: null,
            address_id: 0,
            total_price: 0,
            user_note_value: '',
            is_first: 1,
            is_first_for_score: 1,
            extension_data: [],
            payment_id: 0,
            common_order_is_booking: 0,

            //用户积分数
            user_score: 0,

            true_use_score: 0,
            true_cut_money: 0,
            write_score: 0,
            write_money:0,

            have_no_much_score: false,
			common_site_type: 0,
			extraction_address: [],
			site_model: 0,
			buy_header_nav: [
			    { name: '快递邮寄', value: 0 },
			    { name: '自提点取货', value: 2 },
			],
        };
    },
    onLoad(params) {
		if ((params.data || null) != null && app.globalData.get_length(JSON.parse(decodeURIComponent(params.data))) > 0) {
		    this.setData({
		        params: JSON.parse(decodeURIComponent(params.data))
		    });
			
		    // 删除地址缓存
		    uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key);
		}
    },
    onShow() {
        app.globalData.page_event_onshow_handle();
		
        this.init();
    },
    methods: {
        // 获取数据列表
        init() {
            // 订单参数信息是否正确
            if (this.params == null) {
                this.setData({
                    data_list_loding_status: 2,
                    data_list_loding_msg: this.$t('common.no_relevant_data_tips'),
                });
                uni.stopPullDownRefresh();
                return false;
            }
			
			// 本地缓存地址
			if (this.is_first == 0) {
				var cache_address = uni.getStorageSync(app.globalData.data.cache_buy_user_address_select_key);
				if ((cache_address || null) != null) {
				    this.setData({
				        address: cache_address,
				        address_id: cache_address.id
				    });
				}
			} 
			
			// 加载loding
            uni.showLoading({
                title: this.$t('common.loading_in_text'),
            });
            this.setData({
                data_list_loding_status: 1
            });
            var data = this.params;
            data['address_id'] = this.address_id;
            data['payment_id'] = this.payment_id;
			data['site_model'] = this.site_model;
            uni.request({
                url: app.globalData.get_request_url('buy', 'index', 'scorestore'),
                method: 'POST',
                data: data,
                dataType: 'json',
                success: (res) => {
                    uni.hideLoading();console.log(res);
                    if (res.data.code == 0) {
                        var data = res.data.data;
						var goods_list = data.goods_list || [];
                        if (goods_list.length == 0) {
                            this.setData({
                                data_list_loding_status: 0
                            });
                        } else {
                            var can_score_all = data.score_bili * data.base.is_score;
							var common_site_type = 4;//快递+自提
							if(parseInt(goods_list[0].type) == 1)
							{
								// 虚拟
								common_site_type = 1;
							}else{
								// 实物分仅快递和仅自提
								if(goods_list[0].sendtype == 1)
								{
									// 仅快递
									common_site_type = 0;
								}else if(goods_list[0].sendtype == 2)
								{
									// 仅自提
									common_site_type = 2;
								}
							}
                            this.setData({
								common_site_type: common_site_type,
                                goods_list: goods_list,
                                total_price: data.base.actual_price,
                                extension_data: data.extension_data || [],
                                data_list_loding_status: 3,
                                common_order_is_booking: data.common_order_is_booking || 0,
                                user_score: data.user_score,
								payment_id: data.payment_id || 0,
								extraction_address: data.base.extraction_address || [],
								is_first: 0,
                            }); 
							
							//如果积分不够支付
                            if (parseInt(data.user_score) < parseInt(data.base.actual_price)) {
                                this.setData({
                                    buy_submit_disabled_status: true,
									have_no_much_score: true,
                                });
                            } 
							
							// 地址
							this.setData({
							    address: data.base.address || null,
							    address_id: (data.base.address || null) != null ? data.base.address.id : null
							});
							uni.setStorage({
							    key: app.globalData.data.cache_buy_user_address_select_key,
							    data: data.base.address || null
							});
							
							// 支付方式
                            this.payment_list_data(data.payment_list);
                        }
                    } else {
                        this.setData({
                            data_list_loding_status: 2,
                            data_list_loding_msg: res.data.msg
                        });
                        app.globalData.showToast(res.data.msg);
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    this.setData({
                        data_list_loding_status: 2,
                        data_list_loding_msg: this.$t('common.internet_error_tips')
                    });
                    app.globalData.showToast(this.$t('common.internet_error_tips'));
                }
            });
        },
		
		// 地址选择事件
		address_event(e) {
			// 带上参数
			var json = this.params || null;
			if (json != null) {
			    var params =
			        '&' +
			        Object.keys(json)
			            .map(function (key) {
			                var temp_val = json[key] === undefined || json[key] === null ? '' : json[key];
			                return encodeURIComponent(key) + '=' + encodeURIComponent(temp_val);
			            })
			            .join('&');
			} else {
			    var params = '';
			}
			// 仅自提和快递需要选择地址
			if (this.common_site_type == 0 || (this.common_site_type == 4 && this.site_model == 0)) {
			    app.globalData.url_open('/pages/user-address/user-address?is_back=1' + params);
			} else if (this.common_site_type == 2 || (this.common_site_type == 4 && this.site_model == 2)) {
			    app.globalData.url_open('/pages/extraction-address/extraction-address?is_back=1&is_buy=1' + params);
			} else {
			    app.globalData.showToast(this.$t('buy.buy.31616e'));
			}
		},
		
		// 销售+自提 模式选择事件
		buy_header_nav_event(e) {
		    var value = e.currentTarget.dataset.value || 0;
		
		    if (value != this.site_model) {
		        // 数据设置
		        this.setData({
		            address: null,
		            address_id: null,
		            site_model: value
		        }); // 删除地址缓存
		
		        uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key); // 数据初始化
		
		        this.init();
		    }
		},

        // 用户留言事件
        bind_user_note_event(e) {
            this.setData({
                user_note_value: e.detail.value
            });
        },

        // 提交订单
        buy_submit_event(e) {
			if(this.have_no_much_score)
			{
				app.globalData.showToast('积分不足');
				return false;
			}
            uni.showModal({
                title: '温馨提示',
                content: '一旦提交，将会直接扣除积分，且不支持退换货，确定吗？',
                confirmText: '确认',
                cancelText: '取消',
                success: (result) => {
                    if (result.confirm) {
                        // 表单数据
                        var data = this.params;
                        data['address_id'] = this.address_id;
                        data['payment_id'] = this.payment_id;
                        data['user_note'] = this.user_note_value; // 数据验证
						data['goods_type'] = this.goods_list[0].type;
						data['site_model'] = this.site_model;
						
                        var validation = [];

                        if (app.globalData.fields_check(data, validation)) {
                            // 加载loding
                            uni.showLoading({
                                title: '提交中...'
                            });
                            this.setData({
                                buy_submit_disabled_status: true
                            }); //console.log('------------------------------------------------提交的数据：' + JSON.stringify(data))

                            uni.request({
                                url: app.globalData.get_request_url('orderadd', 'index', 'scorestore'),
                                method: 'POST',
                                data: data,
                                dataType: 'json',
                                success: (res) => {console.log(res);
                                    uni.hideLoading(); 
                                    if (res.data.code == 0) {
                                        if (res.data.data.order.status == 1) {
                                            app.globalData.url_open('/pages/fcc/scorestore/order/order?is_pay=1&order_id=' + res.data.data.order.id, true);
                                        } else {
                                            app.globalData.url_open('/pages/fcc/scorestore/order/order', true);
                                        }
                                    } else {
                                        app.globalData.showToast(res.data.msg);
                                        this.setData({
                                            buy_submit_disabled_status: false
                                        });
                                    }
                                },
                                fail: () => {
                                    uni.hideLoading();
                                    this.setData({
                                        buy_submit_disabled_status: false
                                    });
                                    app.globalData.showToast(this.$t('common.internet_error_tips'));
                                }
                            });
                        }
                    }
                }
            });
        },

        // 支付方式选择
        payment_event(e) {
            this.setData({
                payment_id: e.currentTarget.dataset.value
            });
            this.payment_list_data(this.payment_list);
            this.init();
        },

        // 支付方式数据处理
        payment_list_data(data) {
            if (this.payment_id != 0) {
                for (var i in data) {
                    if (data[i]['id'] == this.payment_id) {
                        data[i]['selected'] = 'selected';
                    } else {
                        data[i]['selected'] = '';
                    }
                }
            }

            this.setData({
                payment_list: data || []
            });
        },

        radioChange(e) {
            var val = e.detail.value;

            if (val == 0) {
                // 不使用积分
                this.setData({
                    true_use_score: 0,
                    true_cut_money: 0
                });
                this.init();
            } else {
                if (this.write_score && this.write_money) {
                    this.setData({
                        true_use_score: this.write_score,
                        true_cut_money: this.write_money
                    });
                } else {
                    this.setData({
                        true_use_score: uni.getStorageSync('true_use_score_back') || -1,
                        true_cut_money: uni.getStorageSync('true_cut_money_back') || 0
                    });
                }

                this.init();
            }
        },

        logInput: function (e) {
            var val = e.detail.value; //输入必须为数字isNaN(parseFloat(val))

            if (val != '' && val != '0') {
                console.log(val + '**--*' + this.true_use_score_back);

                if (parseFloat(val) > parseFloat(this.true_use_score_back)) {
                    this.setData({
                        write_score: this.true_use_score_back,
                        write_money: this.true_cut_money_back
                    });
                } else {
                    if (parseFloat(val) <= parseFloat(this.true_use_score_back) && parseFloat(val) >= 0) {
                        this.setData({
                            write_score: val,
                            write_money: parseFloat(parseFloat(val) / parseFloat(this.score_bili)).toFixed(2)
                        });
                        console.log(this.write_money);
                    } else {
                        app.globalData.showToast('输入正确的数字');
                    }
                }
            } else {
                if (val == '0') {
                    this.setData({
                        write_score: this.true_use_score_back,
                        write_money: this.true_cut_money_back
                    });
                } else {
                    console.log(val + '***' + this.true_use_score_back);
                }
            }
        },

        outinput(e) {
            //离开焦点，根据输入的值，重新初始化
            if (e.detail.value == '') {
                //暂时不影响结果，如果美化，则考虑这里加个提醒，同时将提交按钮变黑，不输入则不允许提交
            }

            if (this.write_score && this.write_money) {
                this.setData({
                    true_use_score: this.write_score
                });
                this.init();
            }
        }
    }
};
</script>
<style>
@import './buy.css';
</style>
